﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SQLite;
using Xamarin.Forms;

namespace Database {
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage {
        public MainPage() {
            InitializeComponent();
        }

        private SQLiteAsyncConnection connection = null;

        private async void CreateDatabaseButton_OnClicked(object sender,
            EventArgs e) {
            var databasePath =
                Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder
                        .LocalApplicationData), "MyData.db");

            connection = new SQLiteAsyncConnection(databasePath);
            await connection.CreateTableAsync<Favorite>();
        }

        private Random random = new Random();

        private async void InsertDataButton_OnClicked(object sender,
            EventArgs e) {
            var favorite = new Favorite
                {IsFavorite = random.NextDouble() > 0.5};
            await connection.InsertAsync(favorite);
        }

        private async void ReadDataButton_OnClicked(object sender,
            EventArgs e) {
            ResultListView.ItemsSource =
                await connection.Table<Favorite>().ToListAsync();
        }
    }

    public class Favorite {
        [PrimaryKey, AutoIncrement] public int Id { get; set; }
        public bool IsFavorite { get; set; }
    }
}